import axios from "axios";
import {getInfoUrl, getPagesUrl} from "../../constant/pixivUrls.js";

export default class BrowserPixivAPI {
    /**
     * @type string
     */
    hosts

    /**
     * @type {AxiosInstance}
     */
    axios

    constructor(requestKwargs = {}) {
        this.hosts = 'https://www.pixiv.net'
        this.axios = axios.create(requestKwargs)
    }

    /**
     * Set proxy hosts
     * @param {string} proxyHosts - Proxy host URL (e.g., "http://app-api.pixivlite.com")
     */
    setApiProxy(proxyHosts) {
        this.hosts = proxyHosts;
    }

    /**
     * Make an API request
     * @private
     */
    async _request(method, url, headers = {}, params = null, data = null) {
        const headers_ = { ...headers };
        const config = {
            method,
            url,
            headers: headers_,
            params,
            data,
        };

        try {
            const response = await this.axios(config);
            return response.data;
        } catch (error) {
            if (error.response) {
                throw new Error(`API request failed: ${error.response.status} - ${JSON.stringify(error.response.data)}`);
            } else {
                throw new Error(`API request failed: ${error.message}`);
            }
        }
    }

    /**
     * 获取作品详情
     * @param illustId 作品id
     * @return {Promise<BrowserIllustResponse|undefined>}
     */
    async illustDetail(illustId) {
        const url = `${this.hosts}/ajax/illust/${illustId}`
        return this._request('GET', url, {}, {}, null)
    }

    /**
     * 获取作品资源
     * @param illustId
     * @return {Promise<BrowserIllustPagesResponse|undefined>}
     */
    async illustPages(illustId) {
        const url = `${this.hosts}/ajax/illust/${illustId}/pages`
        return this._request('GET', url, {}, {}, null)
    }
}
